<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>模板管理</title>
	<meta name="decorator" content="default"/>
    <link href="${ctxStatic}/draging/css/style.css" type="text/css" rel="stylesheet" />
    <script src="${ctxStatic}/draging/js/drag.js" type="text/javascript"></script>
       <script src="${ctxStatic}/jquery-plugin/colpick.js" type="text/javascript"></script>
	<link href="${ctxStatic}/jquery-plugin/colpick.css" type="text/css" rel="stylesheet" />
   <%-- <script src="${ctxStatic}/draging/idrag.js" type="text/javascript"></script>--%>

    <style>
        .tu-con{/*width: 1200px;*/margin-top: 30px;}
        .tu-con .box-par{/*width: 750px;*/float: left;}
        .tu-con .tu-con-sou{width: 130px;float: left;margin-top: 30px;}
        .tu-con .tu-con-sou .tu-con-item{width: 120px;cursor: pointer;position: relative;border: 1px #357ebd solid;margin-top: -1px;}
        .tu-con .tu-con-sou >img{width: 50px;height: 50px;}
        .tu-con .tu-con-sou .tu-con-item span{text-align: center;}
        .tu-con .tu-con-sou .tu-con-item .tu-cur{position: absolute; bottom: 0; right: 0;}
        .tu-con .tu-con-sou .tu-con-item .tu-cur img { width: 25px; display: block; }
        dl{margin-bottom: 0!important;}
        .coor{ cursor: se-resize; background: #797878; height: 18px; width: 18px; position: absolute; bottom: -1px; right: -2px; /* z-index: 99;*/ }
        .btn{min-width: inherit;line-height: initial;}
    </style>
	<script type="text/javascript">
        var eleTempletSourceList = {};
        <c:forEach items="${eleTemplet.eleTempletSourceList}" var="source">

        <c:if test="${'apk' != source.sourceType}">
            var ${source.sourceType} = {};
            ${source.sourceType}.delFlag='0';
            ${source.sourceType}.id='${source.id}';
            ${source.sourceType}.sourceType='${source.sourceType}';
            ${source.sourceType}.width=0+${0+source.width};
            ${source.sourceType}.height=0+${0+source.height};
            ${source.sourceType}.xloc=0+${0+source.xloc};
            ${source.sourceType}.yloc=0+${0+source.yloc};

            eleTempletSourceList.${source.sourceType} = ${source.sourceType};
        </c:if>
        </c:forEach>

		$(document).ready(function() {
            var w= $(window).width()-480;
            $(".set-out").width(w);

            $("#inputForm").validate({
				submitHandler: function(form){
					//loading('<spring:message code="common.subbmiting"/>');
                    saveTempeteSource();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});

            $.each(eleTempletSourceList, function(index, value, array) {
                console.log("<spring:message code="common.add"/> 元素:"+value.sourceType);
                var item = $("#img_"+value.sourceType).parent();
                var width = value.width;
                var height = value.height;
                var xloc = value.xloc;
                var yloc = value.yloc;

                addDrapItem(item, width, height, xloc, yloc);
            });
        });
        // 422  ,  1333
		function changeResolution(obj){
            var ObjId = obj.id;
            var h=$("#height").val();
            var w=$("#width").val();
            $(".box-3").css("height", h).css("width", w);
        }

        function saveTempeteSource(){
            var eleTempletId = $("#eleTempletId").val();
            var name = $("#name").val();
            var type =$("#typeId").val();
            var width =$("#width").val();
            var height =$("#height").val();
            var remarks =$("#templet_remarks").val();
            var displaymode =$("#displaymode").val();
			var font = $("#fontId").val();
			var fullscreen = $("#fullscreen").val();
			if(font == null || font==""){
                alertx("缺少字体");
				return;
			}
            if(width<500 || height<500){
                alertx("分辨率必须大于500X500");
                closeLoading();
                return;
            }

            $.each(eleTempletSourceList, function(index, value, array) {
                var sourceType = value.sourceType;
                try{
                    value.xloc = parseInt($("#"+sourceType).css("left").replace("px",""));
                    value.yloc = parseInt($("#"+sourceType).css("top").replace("px",""));
                }catch (e){}
                eleTempletSourceList[sourceType] = value;
            });
            /*var flag = true;
            $.each(eleTempletSourceList, function(index, value, array) {
                var itemwidth = value.width;
                var itemheight = value.height;
                if (itemwidth > width || itemheight > height) {
                    alertx("设置页面资源大小超过屏幕分辨率!");
                    flag = false;
                    closeLoading();
                    return false;
                }
                var xloc = value.xloc;
                var yloc = value.yloc;
                alert(xloc+itemwidth);
                alert(yloc+itemheight);
                if(xloc+itemwidth > width || yloc+itemheight > height){
                    alertx("设置页面资源超出屏幕边缘!");
                    flag = false;
                    closeLoading();
                    return false;
                }
            });
            if(!flag){
                return;
            }*/

            $.ajax({
                type: "post",
                url: "${ctx}/templet/eleTemplet/saveTempeteSource",
                data: {eleTempletId: eleTempletId,
                    name: name,
                    type: type,
                    width: width,
                    height: height,
                    displaymode: displaymode,
                    remarks: remarks,
                    fullscreen: fullscreen,
                    font:font,
                    eleTempletSourceList: JSON.stringify(eleTempletSourceList)},
                dataType: "JSON",
                success: function(result) {
                    if('0001' == result.code){
                        window.location.href="${ctx}/templet/eleTemplet/show?id=" + result.data;
                    }
                }
            });
        }

        function addDrapItem(obj, width, height, xloc, yloc) {
            var img = $(obj).find(".tit_img").clone();
            var dlId = img.attr("id").split("_")[1];
            var source = eleTempletSourceList[dlId];

            var con_cur = $(obj).find(".tu-cur");
            if (con_cur.length > 0) {
                $("#" + dlId).remove();
                con_cur.remove();
                source.delFlag = 1;
                eleTempletSourceList[dlId] = source;
            } else {
                if (source) {
                    width = parseInt(source.width);
                    height = parseInt(source.height);
                    xloc = parseInt(source.xloc);
                    yloc = parseInt(source.yloc);
                }

                var css = " style='";
                css += width ? "width:" + width + "px;" : "0px;";
                css += height ? "height:" + height + "px;" : "0px;";
                css += xloc ? "left:" + xloc + "px;" : "0px;";
                css += yloc ? "top:" + yloc + "px;" : "0px;";
                css+="background: rgb(238, 238, 238);border: 1px dashed  rgb(171, 171, 171);box-sizing: border-box;";
                css += "' ";
                /*console.log(css);*/

                img.css("width", "50px");
                img.css("height", "50px");

               /* var margin_left = width/2-25<0?0:width/2-25;
                img.css("margin-left", margin_left+'px');

                var margin_top = height/2-25<0?0:height/2-25;
                img.css("margin-top", margin_top+'px');
*/
                img.attr("id", "img_"+dlId);
                img.attr("class","hander");
                img.attr("onmousedown","selectSource('"+dlId+"')");
                img.attr("onmouseup","setSourcePosition('"+dlId+"')");
                /*img.attr("onmousemove","setSourcePosition('"+dlId+"')");*/

                var dl = "<dl id='" + dlId + "' " + css + ">"
                    + img[0].outerHTML
                    + "<div  class='coor' id='co" + dlId + "'></div></dl>";

                $('#box').append(dl);
                $('#' + dlId).dragging({
                    move: 'both',
                    randomPosition: false,
                    width: "800px",
                    height: "600px",
                    hander: '.hander'
                });

                bindResize(document.getElementById(dlId),"co"+dlId);
                selectSource(dlId);

                var cur = "<div class='tu-cur'><img src='${ctxStatic}/images/source/cur.png'></div>";
                $(obj).append(cur);

                $('.coor').bind('mousedown',function () {

                   var id=this.id;
                    var str = id.substring(2,id.length);
                    /*obj=$("#"+str);*/
                    bindResize(document.getElementById(str),id);
                   /* bindResize(obj,id);*/
                    console.log("进程序"+obj+id);
                    selectSource(str);
                    console.log("执行完"+dlId);

                });
            }
        }
//        function bind(e)
//        {
//         /* var a= $(this).id();*/
//            console.log(a);
//            //绑定需要拖拽改变大小的元素对象
//            //bindResize(document.getElementById('test'));
//        }
        function bindResize(el,id)
        {
            //初始化参数
            console.log("进了bindResize");
            console.log(el,id);
            var els = el.style,
                //鼠标的 X 和 Y 轴坐标
                x  = 0;
            y=$("#box")[0].offsetTop;
            console.log(els);
            $("#"+id).mousedown(function (e)
            {   bh=$("#box")[0].offsetTop;
                h=el.offsetTop;
                //按下元素后，计算当前鼠标与对象计算后的坐标
                x = e.pageX - el.offsetWidth,
                    y = e.pageY- bh;
                console.log("移动X"+x+"还有y"+y);
                console.log("鼠标位置X"+e.clientX+"获取鼠标"+e.clientY);
                console.log("鼠标位置X"+e.offsetX+"获取鼠标"+e.offsetX);
                console.log("元素宽"+el.offsetWidth+"获取宽高"+el.offsetHeight);
                //在支持 setCapture 做些东东
                el.setCapture ? (
                    //捕捉焦点
                    el.setCapture(),
                        //设置事件
                        el.onmousemove = function (ev)
                        {
                            mouseMove(ev || event);
                        },
                        el.onmouseup = mouseUp
                ) : (
                    //绑定事件
                    $(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp)
                );
                //防止默认事件发生
                e.preventDefault();

            });
            //移动事件
            function mouseMove(e)
            {
                h=$("#box")[0].offsetTop;
                oh=el.offsetTop;;
                els.width = e.pageX - x + 'px';
                els.height = e.pageY-h - oh + 'px';
              /*  console.log(els.width+"移动"+els.height);*/

                var sourceType = $("#" + id).parent().attr("id");
                var source = eleTempletSourceList[sourceType];
                var screenWidth = parseInt($("#width").val());
                var screenHeight = parseInt($("#height").val());
                var left = parseInt($("#"+sourceType).css("left").replace("px",""));
                var top = parseInt($("#"+sourceType).css("top").replace("px",""));
                source.width = els.width;
                if ((parseInt(els.width)+left)>screenWidth){
                    source.width = els.width=screenWidth-left+'px';
                }
                source.height = els.height;
                if ((parseInt(els.height)+top)>screenHeight){
                    source.height = els.height=screenHeight-top+'px';
                }

                $("#source_width").val(parseInt(els.width));
                $("#source_height").val(parseInt(els.height));
            }
            //停止事件
            function mouseUp()
            {
                el.releaseCapture ? (
                    //释放焦点
                    el.releaseCapture(),
                        //移除事件
                        el.onmousemove = el.onmouseup = null
                ) : (
                    //卸载事件
                    $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp)
                );
            }
        }
        function selectSource(sourceType) {

            var source = eleTempletSourceList[sourceType];
            if(!source){
                source = {};
                source.id = "";
                source.sourceType = sourceType;
                source.width = 50;
                source.height = 50;
                source.xloc = 0;
                source.yloc = 0;
            }
            source.delFlag = 0;
            var sw = parseInt(source.width);
            var sh = parseInt(source.height);

            $("#temSourceId").val(source.id);
            $("input[name='sourceType']").val(sourceType);
            $("#source_width").val(sw);
            $("#source_height").val(sh);

            var source_left = $("#"+sourceType).css("left").replace("px","");
            if(isNaN(source_left)){
                source_left = 0;
            }
            source.xloc = parseInt(source_left);

            var source_top = $("#"+sourceType).css("top").replace("px","");
            if(isNaN(source_top)){
                source_top = 0;
            }
            source.yloc = parseInt(source_top);

            $("#xloc").val(parseInt(source.xloc));
            $("#yloc").val(parseInt(source.yloc));

            eleTempletSourceList[sourceType] = source;
        }

        function mgrInput(sourceType){
            var respath = $("input[name='respath']").parent().parent();
            var respath2 = $("input[name='respath2']").parent().parent();
            var remarks = $("#remarks").parent().parent();

        }

        function setSourcePosition(sourceType){
            console.log(sourceType);
            var source = eleTempletSourceList[sourceType];
            if(!source){
                source = {};
            }

            source.xloc = parseInt($("#xloc").val());
            source.yloc = parseInt($("#yloc").val());

            eleTempletSourceList[sourceType] = source;
            console.log(eleTempletSourceList[sourceType]);
        }

        function inputChange(obj) {
            var inputval = parseInt($(obj).val());
            if (isNaN(inputval)) {
                return;
            }
            if (inputval < 0) {
                inputval = Math.abs(inputval);
            }

            inputval = Math.round(inputval);

            var screenWidth = parseInt($("#width").val());
            var screenHeight = parseInt($("#height").val());


            var sourceType = $("input[name='sourceType']").val();

            var source = eleTempletSourceList[sourceType];
            var left = parseInt($("#"+sourceType).css("left").replace("px",""));
            var top = parseInt($("#"+sourceType).css("top").replace("px",""));
            var name = obj.name;
            source[name] = inputval;

            var obj_img = $("#" + sourceType);

            if (name == 'width') {
                if (inputval > screenWidth) {
                    inputval = screenWidth-left;
                }
                obj_img.css(name, parseInt(inputval) + "px");
                eleTempletSourceList[sourceType].width=parseInt(inputval);
            } else if (name == 'height') {
                if (inputval > screenHeight) {
                    inputval = screenHeight-top;
                }
                obj_img.css(name, parseInt(inputval) + "px");
                eleTempletSourceList[sourceType].height=parseInt(inputval);
            }else if (name == 'xloc') {
                if ((inputval+parseInt(eleTempletSourceList[sourceType].width)) > screenWidth) {
                    inputval = screenWidth-parseInt(eleTempletSourceList[sourceType].width);
                }
                obj_img.css('left', inputval + "px");
            } else if (name == 'yloc') {
                if ((inputval+parseInt(eleTempletSourceList[sourceType].height)) > screenHeight) {
                    inputval = screenHeight-parseInt(eleTempletSourceList[sourceType].height);
                }
                obj_img.css('top', inputval + "px");
            }
            $(obj).val(inputval);
        }
        $(document).ready(function() {
        	$("input[name='background.color']").colpick({
     			layout:'hex',
     			submit:0,
     			colorScheme:'dark',
     			color:'${eleSourceBackground.color}',
     			onChange:function(hsb,hex,rgb,el,bySetColor) {
     				$(el).css('border-color','#'+hex);
     				if(!bySetColor){
     					$(el).val('#'+hex);
     				}
     			}
     		}).keyup(function(){
     			$(this).colpickSetColor(this.value);
     		});
        });
	</script>
</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/templet/eleTemplet/">模板列表</a></li>
		<li class="active"><a href="${ctx}/templet/eleTemplet/form?id=${eleTemplet.id}">模板<shiro:hasPermission name="templet:eleTemplet:edit">${not empty eleTemplet.id?'<spring:message code="common.modify"/>':'<spring:message code="common.add"/>'}</shiro:hasPermission><shiro:lacksPermission name="templet:eleTemplet:edit">查看</shiro:lacksPermission></a></li>
	</ul>
	<form:form id="inputForm" modelAttribute="eleTemplet" action="${ctx}/templet/eleTemplet/save" method="post" class="breadcrumb form-search">
		<form:hidden id="eleTempletId" path="id"/><form:hidden path="flag"/>
		<sys:message content="${message}"/>
        <ul class="ul-form">
            <li><label>模板名称：</label>
                <form:input id="name" path="name" htmlEscape="false" maxlength="255" class="input-small required"/>
            </li>
            <!-- 
            <li><label><spring:message code='menu.device.Equipment_Type'/>：</label>
                <sys:treeselect id="type" name="type.id" value="${eleTemplet.type.id}"
                                labelName="type.name" labelValue="${eleTemplet.type.name}"
                                title="<spring:message code='menu.device.Equipment_Type'/>" url="/equipment/eleEquipmentType/treeData" cssClass="input-small required"/>
            </li>
             -->
            <li><label><spring:message code='common.resolution'/>：</label>
                <form:input id="width" path="width" htmlEscape="false" value="${0==eleTemplet.width?800:eleTemplet.width}"
                            maxlength="11" class="input-mini digits required" cssStyle="width: 40px;"
                            onkeyup="changeResolution(this)"/>
                X
                <form:input id="height" path="height" htmlEscape="false" value="${0==eleTemplet.height?600:eleTemplet.height}"
                            maxlength="11" class="input-mini digits required" cssStyle="width: 40px;"
                            onkeyup="changeResolution(this)"/>
            </li>
             
            <li><label>屏幕方向：</label>
                <form:select id="displaymode" path="displaymode" class="input-small" onchange="changeResolution(this);" style="width: 80px;">
                    <form:options items="${fns:getDictList('displaymode')}" itemLabel="label" itemValue="value" htmlEscape="false"/>
                </form:select>
            </li>
            
            <li><label>字体：</label>
              <sys:treeselect id="font" name="font" value="${eleTemplet.font.id}" labelName="font"
                                labelValue="${eleTemplet.font.name}"
                                cssClass="input-small"
                                title="字体选择" url="/source/font/eleSourceFont/treeData" allowInput="false"/>
            </li>
            <li><label><spring:message code='common.remarks'/>：</label>
                <form:input id="templet_remarks" path="remarks" htmlEscape="false" class="input-small "/>
            </li>
            <br>
            <li><label>是否全屏：</label>
                <form:select path="fullscreen" class="input-small ">
                    <form:options items="${fns:getDictList('truefalse')}" itemLabel="label" itemValue="value" htmlEscape="false"/>
                </form:select>
            </li>
             <li><label>背景颜色：</label>
                <form:input id="templet_color" path="background.color" htmlEscape="false" class="input-small " cssStyle="width: 60px;"/>
            </li>
             <li style="width: 350px;overflow: hidden;"><label>背景图片：</label>
                 <div style="width: 260px;float: right;">
                    <form:hidden id="bgImage" path="background.bgImage" htmlEscape="false" maxlength="255" class="input-small"/>
                    <sys:ckfinder input="bgImage" type="images" uploadPath="/source/background/eleSourceBackground" selectMultiple="false"/>
                 </div>
            </li>
             <li style="width: 400px;overflow: hidden;"><label>背景GIF：</label>
                 <div style="width: 310px;float: right;">
                    <form:hidden id="bgGif" path="background.bgGif" htmlEscape="false" maxlength="255" class="input-small"/>
                    <sys:ckfinder input="bgGif" type="gifs" uploadPath="/source/background/eleSourceBackground" selectMultiple="false"/>
                 </div>
            </li>
        </ul>
        <div class="ul-form tu-con">
            <div id="sourceTypeList" class="tu-con-sou">
                <c:forEach items="${fns:getDictList('source_type')}" var="type">
                    <c:if test="${'apk' != type.value}">
                        <div class="tu-con-item" onclick="addDrapItem(this,'50','50','0','0')">
                            <img id="img_${type.value}" class="tit_img" src="${ctxStatic}/images/source/${type.value}.png">
                            <span>${type.label}</span>
                        </div>
                    </c:if>
                </c:forEach>
            </div>
            <div class="box-par">
                <div class="set-out" style="overflow: scroll">
                <div id="box" class='box box-3' style="width:${0==eleTemplet.width?800:eleTemplet.width}px;height:${0==eleTemplet.height?600:eleTemplet.height}px;">
                </div>
                </div>
                <div style="float: right;margin-top: 10px;">
                    <shiro:hasPermission name="templet:eleTemplet:edit">
                        <input id="btnSubmit" class="btn btn-primary" type="submit" value="保存并预览" onclick="$('#flag').val('0');"/>&nbsp;
                    </shiro:hasPermission>
                </div>
            </div>
            <div style="width: 230px;float: left;margin-left: 10px;">
                <form id="inputForm"  method="post" class="form-horizontal">
                    <input type="hidden" id="temSourceId" name="temSourceId"/>
                    <input type="hidden" name="sourceId"/>
                    <input type="hidden" name="sourceType"/>
                    <div class="control-group">
                        <label class="control-label">大小：</label>
                        <div class="controls">
                            宽:<input id="source_width" name="width" class="input-mini" onkeyup="inputChange(this);"/>
                            高:<input id="source_height" name="height" class="input-mini" onkeyup="inputChange(this);"/>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">坐标：</label>
                        <div class="controls">
                            &nbsp;X:<input id="xloc" name="xloc" class="input-mini" onkeyup="inputChange(this);" />
                            &nbsp;Y:<input id="yloc" name="yloc" class="input-mini" onkeyup="inputChange(this);" />
                        </div>
                    </div>
                        <%--<div class="control-group" style="display: none;">
                            <label class="control-label">文件位置：</label>
                            <div class="controls">
                                <form:hidden id="respath" path="respath" htmlEscape="false" maxlength="255" class="input-xlarge"/>
                                <sys:ckfinder input="respath" type="files" uploadPath="/templet/eleTemplet" selectMultiple="false" />
                            </div>
                        </div>
                             <div class="control-group" style="display: none;">
                                <label class="control-label">下行方向：</label>
                                <div class="controls">
                                    <form:hidden id="respath2" path="respath2" htmlEscape="false" maxlength="255" class="input-xlarge"/>
                                    <sys:ckfinder input="respath2" type="files" uploadPath="/templet/eleTemplet" selectMultiple="false"/>
                                </div>
                            </div>
                          < <div class="control-group" style="display: none;">
                                <label class="control-label">文字：</label>
                                <div class="controls">
                                    <input id="remarks" name="remarks" class="input-large " onchange="inputChange(this);"/>
                                </div>
                            </div>--%>
                </form>
            </div>
        </div>
	</form:form>

</body>
</html>